package com.combetter.changxing.ui.base;

import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.databinding.library.baseAdapters.BR;

import java.io.Serializable;

/**
 * Created by Mark.fan on 2018/5/23.
 */

public abstract class BaseFragment <T extends ViewDataBinding, V extends AndroidViewModel> extends Fragment implements BaseUi{
    private View mView;

    protected T mBinding;

    protected V mViewModel;

    protected Context mContext;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (BaseActivity)context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, setLayout(), container, false);
        mView = mBinding.getRoot();
        mViewModel = (V) ViewModelProviders.of(this).get(createViewModel());
        initViewModel();
        init();
        loadData();
        return mView;
    }

    private void initViewModel() {
        Class<V> clzz = createViewModel();
        if (clzz != null) {
            mViewModel = (V) ViewModelProviders.of(this).get(createViewModel());
            //布局里的变量名必须有viewModel;
            mBinding.setVariable(BR.viewModel, mViewModel);
        }
    }

    /**
     * 返回bidng类
     * @return
     */
    public T getBinding() {
        return mBinding;
    }

    public V getViewModel() {
        return mViewModel;
    }


    @Override
    public void startActivity(Class activityName, Parcelable value) {
        Intent intent = new Intent(mContext, activityName);
        intent.putExtra("value", value);
        startActivity(intent);
    }

    @Override
    public void startActivity(Class activityName, Serializable value) {
        Intent intent = new Intent(mContext, activityName);
        intent.putExtra("value", value);
        startActivity(intent);
    }

    public BaseActivity getBaseActivity() {
        if (mContext instanceof BaseActivity) {
            return (BaseActivity) mContext;
        }
        return null;
    }
}
